/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/util/JoyfulUtils.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: JoyfulUtils.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.util;

import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author elancom
 * @date Apr 11, 2012
 */
public abstract class JoyfulUtils {
	public static <T> void forEach(T[] array, ForEach<T> callback) {
		if (callback == null || array == null || array.length == 0) {
			return;
		}

		for (int i = 0; i < array.length; i++) {
			if (!callback.each(i, array[i])) {
				break;
			}
		}
	}

	public static <T> void forEach(Enumeration<T> enums, Each<T> callback) {
		if (callback == null || enums == null) {
			return;
		}

		while (enums.hasMoreElements()) {
			if (!callback.each((enums.nextElement()))) {
				break;
			}
		}
	}

	public static <T> void forEach(Collection<T> coll, ForEach<T> callback) {
		if (callback == null || CollectionUtils.isEmpty(coll)) {
			return;
		}

		if (coll instanceof List) {
			final List<T> list = (List<T>) coll;

			for (int index = 0, len = list.size(); index < len; index++) {
				if (!callback.each(index, list.get(index))) {
					break;
				}
			}
		} else if (coll instanceof Set) {
			final Iterator<T> iter = ((Set<T>) coll).iterator();
			for (int i = 0; iter.hasNext(); i++) {
				final T t = iter.next();
				if (!callback.each(i++, t)) {
					break;
				}
			}
		}
	}

	public static <K, T> void iterEach(Map<K, T> map, IterEach<K, T> callback) {
		if (callback == null || MapUtils.isEmpty(map)) {
			return;
		}

		K key = null;

		for (final Iterator<K> keys = map.keySet().iterator(); keys.hasNext();) {
			if (!callback.each(key = keys.next(), map.get(key))) {
				break;
			}
		}
	}

	public static <T> String join(Collection<T> collection, SimpleJoin<T> join) {
		if (collection == null || collection.isEmpty()) {
			return "";
		}

		if (join == null) {
			join = new CommaJoin<T>();
		}

		final SimpleJoin<T> simpleJoin = join;
		final int size = collection.size();
		final StringBuilder sb = new StringBuilder();

		JoyfulUtils.forEach(collection, new ForEach<T>() {
			@Override
			public boolean each(int index, T value) {
				sb.append(simpleJoin.getValue(value));
				if (index + 1 < size) {
					sb.append(simpleJoin.separator());
				}
				return true;
			}
		});

		return sb.toString();
	}
}
